// document.addEventListener('DOMContentLoaded', function() {
//     // 检查登录状态
//     if (!localStorage.getItem('token')) {
//         window.location.href = 'index.html';
//         return;
//     }

//     // 设置当前用户
//     const user = JSON.parse(localStorage.getItem('user'));
//     if (user && user.name) {
//         document.getElementById('currentUser').textContent = user.name;
//     }

//     // 时间筛选按钮交互
//     const timeButtons = document.querySelectorAll('.time-btn');
//     timeButtons.forEach(button => {
//         button.addEventListener('click', function() {
//             timeButtons.forEach(btn => btn.classList.remove('active'));
//             this.classList.add('active');
//             // 这里添加时间筛选逻辑
//             console.log('选择的时间范围:', this.textContent);
//         });
//     });

//     // 刷新按钮
//     document.getElementById('refreshBtn').addEventListener('click', function() {
//         // 模拟刷新数据
//         console.log('刷新数据...');
//         this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 刷新中';
//         setTimeout(() => {
//             this.innerHTML = '<i class="fas fa-sync-alt"></i> 刷新数据';
//             showToast('数据已刷新', 'success');
//         }, 1000);
//     });

//     // 退出登录
//     document.getElementById('logoutBtn').addEventListener('click', function() {
//         logout();
//     });

//     console.log('当前用户:--------------');
//     document.querySelectorAll('.sidebar-menu li').forEach(item => {
//         item.addEventListener('click', function() {
//             const page = this.dataset.page;
//             console.log('导航到', page);
//             if (page === 'employees') {
//                 window.location.href = 'employees.html';
//             } else if (page === 'settings') {
//                 // 跳转到设置页面
//                 console.log('导航到设置页面');
//                 window.location.href = 'settings.html';
//             }else if (page === 'product'){
//                 window.location.href = 'product.html';
//             }else if (page === 'activities') {
//                 window.location.href = 'activities.html';
//             }
//             else if(page === 'expert'){
//                 window.location.href = 'expert.html';
//             }else if(page === 'order'){
//                 window.location.href = 'order.html';
// }
//         });
//     });

// function logout() {
//     localStorage.removeItem('token');
//     localStorage.removeItem('user');
//     window.location.href = 'index.html';
// }

// function showToast(message, type) {
//     // 实现简单的消息提示
//     const toast = document.createElement('div');
//     toast.className = `toast toast-${type}`;
//     toast.textContent = message;
//     document.body.appendChild(toast);
    
//     setTimeout(() => {
//         toast.remove();
//     }, 3000);
// }
// })







document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (!localStorage.getItem('token')) {
        window.location.href = 'index.html';
        return;
    }

    // 设置当前用户
    const user = JSON.parse(localStorage.getItem('user'));
    if (user && user.name) {
        document.getElementById('currentUser').textContent = user.name;
    }

    // 时间筛选按钮交互
    const timeButtons = document.querySelectorAll('.time-btn');
    timeButtons.forEach(button => {
        button.addEventListener('click', function() {
            timeButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            const timeRange = this.textContent;
            fetchDashboardData(timeRange);
        });
    });

    // 刷新按钮
    document.getElementById('refreshBtn').addEventListener('click', function() {
        const activeTimeBtn = document.querySelector('.time-btn.active');
        const timeRange = activeTimeBtn ? activeTimeBtn.textContent : '今日';
        
        this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 刷新中';
        fetchDashboardData(timeRange).finally(() => {
            this.innerHTML = '<i class="fas fa-sync-alt"></i> 刷新数据';
            showToast('数据已刷新', 'success');
        });
    });

    // 退出登录
    document.getElementById('logoutBtn').addEventListener('click', function() {
        logout();
    });

    // 导航菜单点击事件
    document.querySelectorAll('.sidebar-menu li').forEach(item => {
        item.addEventListener('click', function() {
            const page = this.dataset.page;
            if (page === 'employees') {
                window.location.href = 'employees.html';
            } else if (page === 'settings') {
                window.location.href = 'settings.html';
            } else if (page === 'product') {
                window.location.href = 'product.html';
            } else if (page === 'activities') {
                window.location.href = 'activities.html';
            } else if (page === 'expert') {
                window.location.href = 'expert.html';
            } else if (page === 'order') {
                window.location.href = 'order.html';
            }else if (page === 'farm-management'){
                window.location.href = 'farm.html';
}
        });
    });

    // 初始化加载数据
    fetchDashboardData('今日');

    // 获取仪表盘数据
    async function fetchDashboardData(timeRange) {
        try {
            // 调用本地8080端口的/admin接口
            const response = await fetch(`http://192.168.8.128:8080/admin/dashboard?range=${encodeURIComponent(timeRange)}`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            
            if (!response.ok) {
                throw new Error('获取数据失败');
            }
            
            const data = await response.json();
            updateDashboardUI(data);
        } catch (error) {
            console.error('获取仪表盘数据出错:', error);
            showToast('获取数据失败', 'error');
            // 使用模拟数据作为后备
            updateDashboardUI(getMockData(timeRange));
        }
    }

    // 生成模拟数据
    function getMockData(timeRange) {
        const baseData = {
            productTypes: 248,
            productTrend: 8.5,
            users: 126,
            newUsers: 61,
            todayOrders: 21,
            targetRate: 92,
            productDistribution: [
                { name: '粮食作物', value: 35, color: '#4CAF50' },
                { name: '蔬菜水果', value: 28, color: '#2196F3' },
                { name: '畜禽产品', value: 22, color: '#FFC107' },
                { name: '其他', value: 15, color: '#9C27B0' }
            ],
            userActivity: [
                { level: '高活跃用户', value: 34, percentage: 27 },
                { level: '中活跃用户', value: 61, percentage: 48 },
                { level: '低活跃用户', value: 31, percentage: 25 }
            ],
            recentOrders: [
                { id: '#TRX-2023-0582', product: '优质大米', farmer: '张伟农场', quantity: '50吨', amount: '24,500', status: 'completed' },
                { id: '#TRX-2023-0581', product: '新鲜苹果', farmer: '李娜果园', quantity: '200箱', amount: '8,600', status: 'shipped' },
                { id: '#TRX-2023-0580', product: '有机鸡蛋', farmer: '王强养殖场', quantity: '500盒', amount: '6,750', status: 'processing' },
                { id: '#TRX-2023-0579', product: '绿色蔬菜', farmer: '赵敏菜园', quantity: '150公斤', amount: '3,200', status: 'completed' }
            ]
        };

        // 根据时间范围调整数据
        switch(timeRange) {
            case '本周':
                return {
                    ...baseData,
                    productTypes: 312,
                    productTrend: 12.3,
                    todayOrders: 147,
                    targetRate: 88
                };
            case '本月':
                return {
                    ...baseData,
                    productTypes: 428,
                    productTrend: 15.8,
                    todayOrders: 632,
                    targetRate: 95
                };
            case '全年':
                return {
                    ...baseData,
                    productTypes: 512,
                    productTrend: 22.1,
                    todayOrders: 5231,
                    targetRate: 102
                };
            default: // 今日
                return baseData;
        }
    }

    // 更新UI
    function updateDashboardUI(data) {
        // 更新核心指标
        updateMetricCard(1, data.productTypes, '农产品种类', data.productTrend);
        updateMetricCard(2, data.users, '注册用户', null, data.newUsers);
        updateMetricCard(3, data.todayOrders, '今日交易', null, null, data.targetRate);
        
        // 更新农产品分类占比
        updateProductDistribution(data.productDistribution);
        
        // 更新用户活跃度
        updateUserActivity(data.userActivity);
        
        // 更新最新交易记录
        updateRecentOrders(data.recentOrders);
    }

    function updateMetricCard(index, value, label, trend, newUsers = null, targetRate = null) {
        const card = document.querySelector(`.metric-card:nth-child(${index})`);
        card.querySelector('.metric-value').textContent = value;
        card.querySelector('.metric-label').textContent = label;
        
        if (trend !== null) {
            const trendElement = card.querySelector('.metric-trend');
            trendElement.innerHTML = `<i class="fas fa-arrow-${trend >= 0 ? 'up' : 'down'}"></i> 较上周 ${Math.abs(trend)}%`;
            trendElement.className = `metric-trend ${trend >= 0 ? 'up' : 'down'}`;
        }
        
        if (newUsers !== null) {
            card.querySelector('.metric-trend').innerHTML = `<i class="fas fa-arrow-up"></i> 本月新增 ${newUsers}人`;
        }
        
        if (targetRate !== null) {
            card.querySelector('.metric-comparison').innerHTML = 
                `达成率 <span class="text-${targetRate >= 90 ? 'success' : 'danger'}">${targetRate}%</span> 目标`;
        }
    }

    function updateProductDistribution(distribution) {
        const progressBars = document.querySelector('.progress-bars');
        progressBars.innerHTML = '';
        
        distribution.forEach(item => {
            progressBars.innerHTML += `
                <div class="progress-item">
                    <div class="progress-label">
                        <span>${item.name}</span>
                        <span>${item.value}%</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: ${item.value}%; background-color: ${item.color};"></div>
                    </div>
                </div>
            `;
        });
    }

    function updateUserActivity(activity) {
        const activityLevels = document.querySelector('.activity-levels');
        activityLevels.innerHTML = '';
        
        activity.forEach(item => {
            const levelClass = item.level.includes('高') ? 'high' : item.level.includes('中') ? 'medium' : 'low';
            
            activityLevels.innerHTML += `
                <div class="level-item">
                    <div class="level-dot ${levelClass}"></div>
                    <div class="level-info">
                        <div class="level-label">${item.level}</div>
                        <div class="level-value">${item.value} <span class="text-muted">(${item.percentage}%)</span></div>
                    </div>
                </div>
            `;
        });
    }

    function updateRecentOrders(orders) {
        const tbody = document.querySelector('.styled-table tbody');
        tbody.innerHTML = '';
        
        orders.forEach(order => {
            tbody.innerHTML += `
                <tr>
                    <td>${order.id}</td>
                    <td>${order.product}</td>
                    <td>${order.farmer}</td>
                    <td>${order.quantity}</td>
                    <td>${order.amount}</td>
                    <td><span class="status-badge ${order.status}">${
                        order.status === 'completed' ? '已完成' : 
                        order.status === 'shipped' ? '已发货' : '处理中'
                    }</span></td>
                </tr>
            `;
        });
    }

    function logout() {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = 'index.html';
    }

    function showToast(message, type) {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        document.body.appendChild(toast);
        
        setTimeout(() => {
            toast.remove();
        }, 3000);
    }
});